<template>
  <div v-if="visible" class="modal-overlay" @click.self="handleClose">
    <div class="modal-container">
      <div class="modal-header">
        <h2>编辑个人资料</h2>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <form @submit.prevent="handleSubmit" class="edit-profile-form">
          <!-- 头像上传 -->
          <div class="form-group avatar-group">
            <label class="avatar-label">头像</label>
            <div class="avatar-upload-container">
              <img :src="formData.avatar" alt="用户头像" class="avatar-preview">
              <div class="avatar-upload-overlay">
                <input 
                  type="file" 
                  id="avatar-upload" 
                  accept="image/*" 
                  @change="handleAvatarChange"
                  class="avatar-upload-input"
                >
                <label for="avatar-upload" class="avatar-upload-btn">
                  <span class="upload-icon">📷</span>
                  <span class="upload-text">更换头像</span>
                </label>
              </div>
            </div>
          </div>

          <!-- 用户名 -->
          <div class="form-group">
            <label for="username">用户名</label>
            <input 
              type="text" 
              id="username" 
              v-model="formData.username"
              class="form-input"
              placeholder="请输入用户名"
              maxlength="20"
            >
            <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
          </div>

          <!-- 邮箱 -->
          <div class="form-group">
            <label for="email">邮箱</label>
            <input 
              type="email" 
              id="email" 
              v-model="formData.email"
              class="form-input"
              placeholder="请输入邮箱"
            >
            <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
          </div>

          <!-- 所在地 -->
          <div class="form-group">
            <label for="location">所在地</label>
            <input 
              type="text" 
              id="location" 
              v-model="formData.location"
              class="form-input"
              placeholder="请输入所在地"
              maxlength="50"
            >
          </div>

          <!-- 个人简介 -->
          <div class="form-group">
            <label for="bio">个人简介</label>
            <textarea 
              id="bio" 
              v-model="formData.bio"
              class="form-textarea"
              placeholder="介绍一下自己吧"
              rows="4"
              maxlength="200"
            ></textarea>
            <div class="char-count">{{ formData.bio.length }}/200</div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button class="save-btn" @click="handleSubmit" :disabled="isSubmitting">
          {{ isSubmitting ? '保存中...' : '保存' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userInfo: {
    type: Object,
    required: true
  }
});

// Emits
const emit = defineEmits(['close', 'update']);

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  location: '',
  bio: '',
  avatar: ''
});

// 错误信息
const errors = reactive({
  username: '',
  email: ''
});

// 提交状态
const isSubmitting = ref(false);

// 监听用户信息变化，同步到表单
watch(() => props.userInfo, (newUserInfo) => {
  if (newUserInfo) {
    formData.username = newUserInfo.username || '';
    formData.email = newUserInfo.email || '';
    formData.location = newUserInfo.location || '';
    formData.bio = newUserInfo.bio || '';
    formData.avatar = newUserInfo.avatar || 'https://picsum.photos/seed/useravatar/150/150';
  }
}, { deep: true, immediate: true });

// 处理头像上传
const handleAvatarChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      formData.avatar = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

// 验证表单
const validateForm = () => {
  let isValid = true;
  
  // 重置错误信息
  errors.username = '';
  errors.email = '';
  
  // 验证用户名
  if (!formData.username.trim()) {
    errors.username = '用户名不能为空';
    isValid = false;
  } else if (formData.username.length < 2 || formData.username.length > 20) {
    errors.username = '用户名长度应在2-20个字符之间';
    isValid = false;
  }
  
  // 验证邮箱
  if (formData.email.trim()) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      errors.email = '请输入有效的邮箱地址';
      isValid = false;
    }
  }
  
  return isValid;
};

// 处理表单提交
const handleSubmit = async () => {
  if (!validateForm()) {
    return;
  }
  
  isSubmitting.value = true;
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800));
    
    // 提交成功，触发更新事件
    emit('update', {
      ...formData
    });
    
    // 关闭模态框
    handleClose();
  } catch (error) {
    console.error('保存资料失败:', error);
    alert('保存资料失败，请稍后重试');
  } finally {
    isSubmitting.value = false;
  }
};

// 处理关闭
const handleClose = () => {
  // 重置表单数据
  if (props.userInfo) {
    formData.username = props.userInfo.username || '';
    formData.email = props.userInfo.email || '';
    formData.location = props.userInfo.location || '';
    formData.bio = props.userInfo.bio || '';
    formData.avatar = props.userInfo.avatar || 'https://picsum.photos/seed/useravatar/150/150';
  }
  
  // 清空错误信息
  errors.username = '';
  errors.email = '';
  
  // 触发关闭事件
  emit('close');
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-container {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #718096;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background-color: #f7fafc;
  color: #1a202c;
}

.modal-body {
  padding: 24px;
}

.edit-profile-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #4a5568;
  font-size: 14px;
}

.form-input,
.form-textarea {
  padding: 12px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #4299e1;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.error-message {
  color: #e53e3e;
  font-size: 12px;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #718096;
  margin-top: 4px;
}

/* 头像上传样式 */
.avatar-group {
  align-items: center;
}

.avatar-upload-container {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s ease;
  cursor: pointer;
}

.avatar-upload-container:hover .avatar-upload-overlay {
  opacity: 1;
}

.avatar-upload-input {
  display: none;
}

.avatar-upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  color: #fff;
  cursor: pointer;
}

.upload-icon {
  font-size: 20px;
}

.upload-text {
  font-size: 12px;
}

.modal-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid #e2e8f0;
}

.cancel-btn,
.save-btn {
  padding: 10px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

.cancel-btn {
  background-color: #f7fafc;
  color: #4a5568;
}

.cancel-btn:hover {
  background-color: #edf2f7;
}

.save-btn {
  background-color: #4299e1;
  color: #fff;
}

.save-btn:hover:not(:disabled) {
  background-color: #3182ce;
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .modal-container {
    margin: 10px;
    width: calc(100% - 20px);
  }
  
  .modal-header,
  .modal-body,
  .modal-footer {
    padding: 16px;
  }
}
</style>